package com.chainyoung.trademarket.ui.fragment;

import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.bean.ReqModel;
import com.chainyoung.common.bean.UserInfo;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.http.JsonConventUtils;
import com.chainyoung.common.http.websocket.WebSoketUtils;
import com.chainyoung.common.http.websocket.WsManager;
import com.chainyoung.common.http.websocket.WsStatus;
import com.chainyoung.common.http.websocket.WsStatusListener;
import com.chainyoung.common.appcommon.entity.MarketDetail;
import com.chainyoung.common.utils.CommonUtil;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.chainyoung.trademarket.R;
import com.chainyoung.trademarket.adapter.IndexAdapter;
import com.chainyoung.trademarket.di.component.DaggerMainFragmentComponent;
import com.chainyoung.trademarket.di.module.MainFragmentModule;
import com.chainyoung.trademarket.entity.Ad;
import com.chainyoung.trademarket.entity.IndexApp;
import com.chainyoung.trademarket.entity.IndexData;
import com.chainyoung.trademarket.entity.IndexMarket;
import com.chainyoung.trademarket.mvp.contract.IndexContract;
import com.chainyoung.trademarket.mvp.presenter.IndexPresenter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import okhttp3.Response;
import okio.ByteString;
import q.rorbin.badgeview.QBadgeView;

import static com.chainyoung.common.constant.CommonStringConstants.URL;

@Route(path = RouterConstants.PATH_INDEX)
public class IndexFragment extends BaseFragment<IndexPresenter> implements IndexContract.View {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    private String TAG = getClass().getSimpleName();

    private IndexAdapter adapter;


    private List<MarketDetail> detailList = new ArrayList<>();
    private List<IndexApp> appList = new ArrayList<>();
    private List<Ad> banners = new ArrayList<>();
    private List<Ad> ads = new ArrayList<>();
    /**
     * 消息角标
     */
    private QBadgeView badgeView;

    /**
     * websocket
     */
    private WsManager wsManager;
    // private WsStatusListener wsStatusListener;

    private boolean isAlreadySubed = false;
    private boolean isVisiable;


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMainFragmentComponent.builder()
                .appComponent(appComponent)
                .mainFragmentModule(new MainFragmentModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUi() {
        super.initUi();
        setCurrentTitle(getString(R.string.index));
        showAndSetBarRightIcon(R.mipmap.ic_msg);
        initMsg();
        //showAndSetBarRightLeftIcon(R.mipmap.kefu);
        initRecyclerView();

        wsManager = WebSoketUtils.getWsManager();

    }

    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new IndexAdapter(mContext, detailList, appList, banners, ads);
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData();
            }
        });
    }

    private void initMsg() {
        int num = 0;
        if (CommonUtil.getUserInfo() != null) {
            num = CommonUtil.getUserInfo().getUnread_msg_num();
        }
        if (badgeView == null) {
            badgeView = new QBadgeView(mContext);
            badgeView.setBadgeBackgroundColor(ContextCompat.getColor(mContext, com.chainyoung.component_tmtrade.R.color._F95A54));
            badgeView.setBadgeTextColor(ContextCompat.getColor(mContext, com.chainyoung.component_tmtrade.R.color.white));
            badgeView.setBadgeTextSize(9, true);
            badgeView.bindTarget(mBarRightImageView).setBadgeGravity(Gravity.TOP | Gravity.END).
                    setGravityOffset(4, 3, true).
                    setBadgeNumber(num);
        } else {
            badgeView.setBadgeNumber(num);
        }

    }

//    @Override
//    public void onRightLeftImgClicked(View v) {
//        RouterUtils.getInstance()
//                .build(RouterConstants.PATH_CHAT_ROOM)
//                .withString(URL, CommonUtil.getUserInfo().getH5_chat_url())
//                .navigation();
//    }

    @Override
    protected void initData() {

    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_find;
    }


    @Override
    public void onRightImgClicked(View v) {
        super.onRightImgClicked(v);
        RouterUtils.getInstance()
                .build(RouterConstants.PATH_MESSAGE_CENTER)
                .navigation();

    }

    @Override
    protected void onFirstUserVisible() {
        getData();
        isVisiable = true;
        wsManager.startConnect();
        wsManager.setWsStatusListener(wsStatusListener);


    }

    WsStatusListener wsStatusListener = new WsStatusListener() {
        @Override
        public void onMessage(ByteString bytes) {
            super.onMessage(bytes);
            String r = JsonConventUtils.byteBufferToString(bytes.asByteBuffer());
            try {
                String result = JsonConventUtils.uncompress(r);
                handleResult(result);
                Log.d(TAG, result);
            } catch (IOException e) {
                e.printStackTrace();
            }
            EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.WS_INDEX_OPEN));
        }

        @Override
        public void onFailure(Throwable t, Response response) {
            isAlreadySubed=false;
            super.onFailure(t, response);
            Log.d(TAG, "closed");
        }

        @Override
        public void onOpen(Response response) {
            super.onOpen(response);
            EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.WS_INDEX_OPEN));
        }
    };

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        isVisiable = true;
        if (wsManager.getCurrentStatus() != WsStatus.CONNECTED) {
            wsManager.setWsStatusListener(wsStatusListener);
            wsManager.startConnect();
        }
        getUserInfo();

    }

    @Override
    public void onUserInvisible() {
        super.onUserInvisible();
        if (wsManager.getCurrentStatus() == WsStatus.CONNECTED) {
            ReqModel reqModel1 = new ReqModel();
            reqModel1.setType("unsub");
            reqModel1.setTopic(getMarketName());
            wsManager.sendMessage(new Gson().toJson(reqModel1));
            isAlreadySubed = false;
        }
        wsManager.stopConnect();
        isVisiable = false;
    }

    public void getMarketList() {
        ReqModel reqModel = new ReqModel();
        reqModel.setType("sub");
        reqModel.setTopic(getMarketName());
        wsManager.sendMessage(new Gson().toJson(reqModel));

        ReqModel reqModel1 = new ReqModel();
        reqModel1.setType("req");
        reqModel1.setTopic(getMarketName());
        wsManager.sendMessage(new Gson().toJson(reqModel1));
        isAlreadySubed = true;
    }


    private void handleResult(String marketResult) {
        Gson gson = new Gson();
        IndexMarket indexMarket = null;
        try {
            indexMarket = gson.fromJson(marketResult, new TypeToken<IndexMarket>() {
            }.getType());
        } catch (Exception e) {

        }
        if (indexMarket != null) {
            if (indexMarket.getType().equals("ping")) {
                //发送pong
                sendPong();
            }
            if (indexMarket.getTick() != null && indexMarket.getTopic().equals(getMarketName())) {
                detailList.clear();
                detailList.addAll(indexMarket.getTick());
                int remainedNum = 3 - indexMarket.getTick().size() % 3;

                if (remainedNum == 3) {
                    adapter.notifyItemChanged(1);
                    return;
                }
                for (int i = 0; i < remainedNum; i++) {
                    MarketDetail marketDetail = new MarketDetail();
                    detailList.add(marketDetail);
                }
                adapter.notifyItemChanged(1);
            }

        }


    }

    private void sendPong() {
        ReqModel reqModel = new ReqModel();
        reqModel.setType("pong");
        wsManager.sendMessage(new Gson().toJson(reqModel));
    }


    private String getMarketName() {
        return "market.null.app_market";
    }


    //-------------------------------------------------------------------网络请求-----------------------------------------------------------------------------
    private void getUserInfo() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        mPresenter.getUserInfo(map);
    }

    @Override
    public void onGetIndexAppsFailed() {
        refreshLayout.finishRefresh();
    }

    @Override
    public void onGetUserInfoSuccess(UserInfo userInfo) {
        UserInfo data = CommonUtil.getUserInfo();
        userInfo.setIs_setpaypassword(userInfo.getIs_setpaypassword());
        userInfo.setToken(userInfo.getToken());
        userInfo.setH5_chat_url(userInfo.getH5_chat_url());
        userInfo.setChatId(data.getChatId());
        CommonUtil.setUserInfo(userInfo);
        initMsg();
    }


    private void getData() {

        TreeMap<String, Object> map = new TreeMap<>();
        map.put("limit", "5");
        mPresenter.getIndexData(map);

    }


    @Override
    public void onGetIndexAppsSuccess(IndexData data) {
        refreshLayout.finishRefresh();
        appList.clear();
        banners.clear();
        ads.clear();
        if (data != null) {
            if (data.getBanner() != null) {
                banners.addAll(data.getBanner());
            }
            if (data.getNotice() != null) {
                ads.addAll(data.getNotice());
            }
            if (data.getNavigation() != null) {
                appList.addAll(data.getNavigation());
            }
        }
        adapter.notifyDataSetChanged();

    }


    // ---------------------------------event-------------------------------------

    @Subscriber
    public void onGetMarketList(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.WS_INDEX_OPEN) {
            if (isVisiable && mIsPrepared && !isAlreadySubed) {
                getMarketList();
            }
        }

    }


}
